<script setup>
import Footer from "@/components/common/Footer.vue";
import {onMounted, ref} from "vue";
import { useRouter} from 'vue-router'
import axios from 'axios'
import qs from 'qs'
const token = localStorage.getItem('token');
// 声明响应式数据
const orderArr = ref([])

const router = useRouter()
const user = ref({})
const businessList = ref([])
const foodList = ref([])
// 获取 sessionStorage 中的用户信息
const getUserFromSession = () => {
  const storedUser = sessionStorage.getItem('user')
  if (storedUser) {
    user.value = JSON.parse(storedUser)
  }
}
// 获取所有食品信息
const fetchFoodDetails = async () => {
  try {
    console.log('token:',token);
    const response = await axios.get('food/listAllFood',
        {
          headers: {
           "Authorization": `Bearer ${token}`,
          }
        })
    foodList.value = response.data
  } catch (error) {
    console.error('获取食品信息失败:', error);
  }
}


const routeToPayMent = (order)=>{
  debugger
  
  router.push({path: '/payment', query: {orderId: order.orderId}})
}

// 获取全部商家信息
const fetchBusinessDetails = async () => {
  try {
    const response = await axios.get('business/listAllBusiness',
        {
          headers: {
            "Authorization": `Bearer ${token}`,
          }
        })
    businessList.value = response.data
    console.log(businessList.value)
  } catch (error) {
    console.error('获取商家信息失败:', error)
  }
}

// 请求订单数据
const fetchOrders = async () => {
  try {
    const response = await axios.post('orders/listOrdersByUserId',
        qs.stringify({
          userId: user.value.userId
        }), {
          headers: {
            "Authorization": `Bearer ${token}`,
          }
        })
    const result = response.data
    // 给每个订单添加 `isShowDetailet` 属性
    for (const order of result) {
      order.isShowDetailet = false
      order.business = businessList.value.find(b => b.businessId === order.businessId)
      const orderId = order.orderId
      const orderDetailetResponse = await axios.post('orders/listOrderDetailetByOrderId',
          qs.stringify({
            orderId: orderId
          }), {
            headers: {
              "Authorization": `Bearer ${token}`,
            }
          })
      const detailetResult = orderDetailetResponse.data
      console.log(detailetResult)
      order.list = []
      detailetResult.forEach(odItem => {
        // 找到对应的 foodId
        const food = foodList.value.find(f => f.foodId === odItem.foodId)
        if (food) {
          // 将食物信息添加到订单的 list 中
          order.list.push({
            food: food,
            quantity: odItem.quantity
          })
        }
      })
    }
    console.log(result)
    orderArr.value = result
    console.log(orderArr.value)
  } catch (error) {
    console.error(error)
  }
}

// 切换订单详情显示状态
const detailetShow = (order) => {
  order.isShowDetailet = !order.isShowDetailet
}

onMounted(async () => {
  getUserFromSession()
  await fetchBusinessDetails()
  await fetchFoodDetails()
  await fetchOrders()
})
</script>

<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <p>我的订单</p>
    </header>
    <!-- 订单列表部分 -->
    <h3>未支付订单信息：</h3>
    <ul class="order">
      <li v-for="item in orderArr" v-show="item.orderState === 0" :key="item.orderId">
        <div class="order-info">
          <p>
            {{ item.business.businessName }}
            <i class="fa fa-caret-down" @click="detailetShow(item)"></i>
          </p>
          <div class="order-info-right">
            <p>&#165;{{ item.orderTotal }}</p>
            <div class="order-info-right-icon" @click="routeToPayMent(item)">去支付</div>
          </div>
        </div>
        <ul class="order-detailet" v-show="item.isShowDetailet">
          <li v-for="odItem in item.list" :key="odItem.food.foodId">
            <p>{{ odItem.food.foodName }} x {{ odItem.quantity }}</p>
            <p>&#165;{{ odItem.food.foodPrice * odItem.quantity }}</p>
          </li>
          <li>
            <p>配送费</p>
            <p>&#165;{{ item.business.deliveryPrice }}</p>
          </li>
        </ul>
      </li>
    </ul>
    <h3>已支付订单信息：</h3>
    <ul class="order">
      <li v-for="item in orderArr" v-show="item.orderState === 1" :key="item.orderId">
        <div class="order-info">
          <p>
            {{ item.business.businessName }}
            <i class="fa fa-caret-down" @click="detailetShow(item)"></i>
          </p>
          <div class="order-info-right">
            <p>&#165;{{ item.orderTotal }}</p>
          </div>
        </div>
        <ul class="order-detailet" v-show="item.isShowDetailet">
          <li v-for="odItem in item.list" :key="odItem.food.foodId">
            <p>{{ odItem.food.foodName }} x {{ odItem.quantity }}</p>
            <p>&#165;{{ odItem.food.foodPrice * odItem.quantity }}</p>
          </li>
          <li>
            <p>配送费</p>
            <p>&#165;{{ item.business.deliveryPrice }}</p>
          </li>
        </ul>
      </li>
    </ul>
    <!-- 底部菜单部分 -->
    <Footer/>
  </div>
</template>

<style scoped>
/****************** 总容器 ******************/
.wrapper {
  width: 100%;
  height: 100%;
}

/****************** header部分 ******************/
.wrapper header {
  width: 100%;
  height: 12vw;
  background-color: #0097FF;
  color: #fff;
  font-size: 4.8vw;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
}

/****************** 历史订单列表部分 ******************/
.wrapper h3 {
  margin-top: 12vw;
  box-sizing: border-box;
  padding: 4vw;
  font-size: 4vw;
  font-weight: 300;
  color: #999;
}

.wrapper .order {
  width: 100%;
}

.wrapper .order li {
  width: 100%;
}

.wrapper .order li .order-info {
  box-sizing: border-box;
  padding: 2vw 4vw;
  font-size: 4vw;
  color: #666;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.wrapper .order li .order-info .order-info-right {
  display: flex;
}

.wrapper .order li .order-info .order-info-right .order-info-right-icon {
  background-color: #f90;
  color: #fff;
  border-radius: 3px;
  margin-left: 2vw;
  user-select: none;
  cursor: pointer;
}

.wrapper .order li .order-detailet {
  width: 100%;
}

.wrapper .order li .order-detailet li {
  width: 100%;
  box-sizing: border-box;
  padding: 1vw 4vw;
  color: #666;
  font-size: 3vw;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>